'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { Todo } from '@/types/todo';
import { authStore } from '@/lib/auth';

export default function Home() {
  const [todos, setTodos] = useState<Todo[]>([]);
  const [newTodoText, setNewTodoText] = useState('');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [user, setUser] = useState<any>(null);
  const router = useRouter();

  // 检查用户是否已登录
  useEffect(() => {
    const unsubscribe = authStore.subscribe((currentUser) => {
      setUser(currentUser);
      if (!currentUser) {
        router.push('/login');
      }
    });

    const currentUser = authStore.getUser();
    setUser(currentUser);
    
    if (!currentUser) {
      router.push('/login');
    }

    return () => unsubscribe();
  }, [router]);

  // 获取所有待办事项
  const fetchTodos = async () => {
    if (!user) return;
    
    try {
      setLoading(true);
      const response = await fetch('/api/todos');
      if (!response.ok) throw new Error('Failed to fetch todos');
      const data = await response.json();
      setTodos(data);
      setError(null);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'An error occurred');
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  // 初始加载和刷新数据
  useEffect(() => {
    if (user) {
      fetchTodos();
    }
  }, [user]);

  // 添加新的待办事项
  const handleAddTodo = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newTodoText.trim() || !user) return;

    try {
      const response = await fetch('/api/todos', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ text: newTodoText }),
      });

      if (!response.ok) throw new Error('Failed to add todo');
      
      const newTodo = await response.json();
      setTodos([newTodo, ...todos]);
      setNewTodoText('');
    } catch (err) {
      setError(err instanceof Error ? err.message : 'An error occurred');
      console.error(err);
    }
  };

  // 切换待办事项状态
  const handleToggleTodo = async (id: number, currentCompleted: boolean) => {
    try {
      const response = await fetch(`/api/todos/${id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ completed: !currentCompleted }),
      });

      if (!response.ok) throw new Error('Failed to update todo');
      
      const updatedTodo = await response.json();
      setTodos(todos.map(todo => 
        todo.id === id ? updatedTodo : todo
      ));
    } catch (err) {
      setError(err instanceof Error ? err.message : 'An error occurred');
      console.error(err);
    }
  };

  // 删除待办事项
  const handleDeleteTodo = async (id: number) => {
    try {
      const response = await fetch(`/api/todos/${id}`, {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
      });

      if (!response.ok) throw new Error('Failed to delete todo');
      
      setTodos(todos.filter(todo => todo.id !== id));
    } catch (err) {
      setError(err instanceof Error ? err.message : 'An error occurred');
      console.error(err);
    }
  };

  // 用户登出
  const handleLogout = () => {
    authStore.setUser(null);
    router.push('/login');
  };

  if (!user) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto"></div>
          <p className="mt-4 text-gray-600">正在加载...</p>
        </div>
      </div>
    );
  }

  return (
    <main className="min-h-screen bg-gray-50 py-10 px-4 sm:px-6 lg:px-8">
      <div className="max-w-3xl mx-auto bg-white rounded-lg shadow-md overflow-hidden">
        <div className="px-6 py-4 border-b border-gray-200 flex justify-between items-center">
          <h1 className="text-2xl font-bold text-gray-800">Todo List</h1>
          <div className="flex items-center space-x-4">
            <span className="text-gray-600">欢迎, {user.username}!</span>
            <button
              onClick={handleLogout}
              className="px-4 py-2 text-sm bg-gray-100 hover:bg-gray-200 rounded-md transition"
            >
              登出
            </button>
          </div>
        </div>
        
        <form onSubmit={handleAddTodo} className="px-6 py-4 border-b border-gray-200">
          <div className="flex space-x-2">
            <input
              type="text"
              value={newTodoText}
              onChange={(e) => setNewTodoText(e.target.value)}
              placeholder="添加新的待办事项..."
              className="flex-1 px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
            <button
              type="submit"
              className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
            >
              添加
            </button>
          </div>
        </form>
        
        {error && (
          <div className="px-6 py-4 bg-red-50 text-red-600">
            {error}
          </div>
        )}
        
        <div className="divide-y divide-gray-200">
          {loading ? (
            <div className="px-6 py-4 text-gray-500">加载中...</div>
          ) : todos.length === 0 ? (
            <div className="px-6 py-4 text-gray-500">还没有待办事项。添加一个新的开始吧！</div>
          ) : (
            todos.map((todo) => (
              <div key={todo.id} className="px-6 py-4 flex items-center justify-between">
                <div className="flex items-center space-x-3">
                  <input
                    type="checkbox"
                    checked={todo.completed}
                    onChange={() => handleToggleTodo(todo.id, todo.completed)}
                    className="h-5 w-5 text-blue-500 focus:ring-blue-500 border-gray-300 rounded"
                  />
                  <span className={`${todo.completed ? 'line-through text-gray-500' : ''}`}>
                    {todo.text}
                  </span>
                </div>
                <button
                  onClick={() => handleDeleteTodo(todo.id)}
                  className="text-red-500 hover:text-red-700 focus:outline-none"
                >
                  删除
                </button>
              </div>
            ))
          )}
        </div>
      </div>
    </main>
  );
}